<?php
// +----------------------------------------------------------------------
// | 众联TK架构 [ ZoomTk ]
// +----------------------------------------------------------------------
// | 版权所有 2017~2037 成都众联思索科技有限公司 [ http://www.zoomtk.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://www.sopvip.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
namespace app\mall\home\seller;
/**
 * 前台首页控制器
 * @package app\cms\admin
 */
class Goodsadd extends BaseSeller
{
    /**
     * 首页
     * @author Sunday <153788231@qq.com>
     * @return mixed
     */
    public function index()
    {
        // 实例化商品分类模型
        $model_goodsclass = Model('goodsclass');
        // 商品分类
        $goods_class = $model_goodsclass->getGoodsClass(session('store_id'), 0, 1, session('seller_group_id'), session('seller_gc_limits'));
        // 常用商品分类
        $model_staple = Model('goodsclassstaple');
        $param_array = array();
        $param_array['member_id'] = session('member_id');
        $staple_array = $model_staple->getStapleList($param_array);
        $this->assign('staple_array', $staple_array);
        $this->assign('goods_class', $goods_class);
        return  $this->fetch('goodsadd_step1');
    }

    /***
     * @return mixed
     * 添加商品第二步
     */
    public function add_step_two(){
        if (input('caiji_id') != '') {
            $opts = array(
                'http' => array(
                    'method' => "GET",
                    'timeout' => 60,
                )
            );
            set_time_limit(0);
            $context = stream_context_create($opts);
            $id =input('caiji_id');
            $text = file_get_contents("http://hws.alicdn.com/cache/mtop.wdetail.getItemDescx/4.1/?data={'item_num_id':{$id}}", false, $context);
            $json = file_get_contents("http://hws.alicdn.com/cache/wdetail/5.0/?id={$id}", false, $context);
            $data = json_decode($json, 1);
            $texts = json_decode($text, 1);
            if ($texts['data']['pages']) {
                $content = "";
                foreach ($texts['data']['pages'] as $p) {
                    $content .= $p;
                }
                $content = str_replace("<img>", "<img src=", $content);
                $content = str_replace("</img>", ">", $content);
                $content = str_replace("txt", "p", $content);
            }
            $goods_body['goods_body'] = $content;
            if (!empty($data['data']['itemInfoModel']['picsPath'])) {
                $imgs = $this->gteImg($data['data']['itemInfoModel']['picsPath']);
            }
            $image_dir_type = $this->image_dir_type();
            foreach ($imgs as $val) {
                $imgArr[] = UPLOAD_SITE_URL . $image_dir_type . $val;
            }
            $str_img = implode(',', $imgs);
            $this->assign('str_img', $str_img);
            $this->assign('img_name', $imgs);
            $this->assign('imgArr', $imgArr);
            $this->assign('caiji', $data);
            $this->assign('goods', $goods_body);
        }
        // 实例化商品分类模型
        $model_goodsclass = Model('goodsclass');
        // 现暂时改为从匿名“自营店铺专属等级”中判断
        $editor_multimedia = false;
        if ($this->store_grade['sg_function'] == 'editor_multimedia') {
            $editor_multimedia = true;
        }
        $this->assign('editor_multimedia', $editor_multimedia);

        $gc_id = intval( input('class_id'));
        $this->assign('class_id',  $gc_id);
        // 验证商品分类是否存在且商品分类是否为最后一级
        $data = Model('goods_class')->getGoodsClassForCacheModel();
        if (!isset($data[$gc_id]) || isset($data[$gc_id]['child']) || isset($data[$gc_id]['childchild'])) {
            $this->success('您选择的分类不存在，或没有选择到最后一级，请重新选择分类。');
        }
        // 如果不是自营店铺或者自营店铺未绑定全部商品类目，读取绑定分类
        if (!checkStoreBindingAllGoodsClass()) {
            $where['class_1|class_2|class_3'] = $gc_id;
            $where['store_id'] = session('store_id');
            $rs = Model('Storebindclass')->getStoreBindClassInfo($where);
            if (empty($rs)) {
                $this->success('您的店铺没有绑定该分类，请重新选择分类。');
            }
        }
        //权限组对应分类权限判断
        if (!session('seller_gc_limits') && session('seller_group_id')) {
            $rs = Model('sellergroupbclass')->getSellerGroupBclassInfo(array('group_id' => session('seller_group_id'), 'gc_id' => $gc_id));
            if (!$rs) {
                $this->error('您所在的组无权操作该分类下的商品');
            }
        }
        // 更新常用分类信息
        $goods_class = $model_goodsclass->getGoodsClassLineForTag($gc_id);
        $this->assign('goods_class', $goods_class);
        Model('goods_class_staple')->autoIncrementStaple($goods_class, UID);
        // 获取类型相关数据
        $typeinfo = Model('type')->getAttr($goods_class['type_id'], session('store_id'), $gc_id);
        var_dump( $typeinfo);die;
        list($spec_json, $spec_list, $attr_list, $brand_list) = $typeinfo;
        $this->assign('sign_i', count($spec_list));
        $this->assign('spec_list', $spec_list);
        $this->assign('attr_list', $attr_list);
        $this->assign('brand_list', $brand_list);
        //获取分销级别
        $sgrade_model = Model('store_supply_grade');
        $sgrade_list = $sgrade_model->getSupplyGradeList(array('store_id' => session('store_id')));
        $this->assign('sgrade_list', $sgrade_list);
        // 自定义属性
        $custom_list = Model('type_custom')->getTypeCustomList(array('type_id' => $goods_class['type_id']));
        $this->assign('custom_list', $custom_list);
        // 实例化店铺商品分类模型
        $store_goods_class = Model('store_goods_class')->getClassTree(array('store_id' => session('store_id'), 'stc_state' => '1'));
        $this->assign('store_goods_class', $store_goods_class);
        // 小时分钟显示
        $hour_array = array('00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23');
        $this->assign('hour_array', $hour_array);
        $minute_array = array('05', '10', '15', '20', '25', '30', '35', '40', '45', '50', '55');
        $this->assign('minute_array', $minute_array);
        // 关联版式
        $plate_list = Model('store_plate')->getStorePlateList(array('store_id' => session('store_id')), 'plate_id,plate_name,plate_position');
        $plate_list = array_under_reset($plate_list, 'plate_position', 2);
        $this->assign('plate_list', $plate_list);
        // 供货商
        $supplier_list = Model('store_supplier')->getStoreSupplierList(array('sup_store_id' => session('store_id')));
        $this->assign('supplier_list', $supplier_list);
        return  $this->fetch('goodsadd_step2');
    }
    /**
     * ajax获取商品分类的子级数据
     */
    public function ajaxgoodsclass()
    {
        $gc_id = intval(input('gc_id'));
        $deep = intval(input('deep'));
        if ($gc_id <= 0 || $deep <= 0 || $deep >= 4) {
            exit();
        }
        $model_goodsclass = Model('goodsclass');
        $list = $model_goodsclass->getGoodsClass(session('store_id'), $gc_id, $deep, session('seller_group_id'), session('seller_gc_limits'));
        if (empty($list)) {
            exit();
        }
        echo json_encode($list);
    }

    /**
     * ajax删除常用分类
     */
    public function ajaxstapledel() {
        Language::read ( 'member_store_goods_index' );
        $staple_id = intval($_GET ['staple_id']);
        if ($staple_id < 1) {
            echo json_encode ( array (
                'done' => false,
                'msg' => Language::get ( 'wrong_argument' )
            ) );
            die ();
        }
        /**
         * 实例化模型
         */
        $model_staple = Model('goods_class_staple');

        $result = $model_staple->delStaple(array('staple_id' => $staple_id, 'member_id' => $_SESSION['member_id']));
        if ($result) {
            echo json_encode ( array (
                'done' => true
            ) );
            die ();
        } else {
            echo json_encode ( array (
                'done' => false,
                'msg' => ''
            ) );
            die ();
        }
    }
    /**
     * ajax选择常用商品分类
     */
    public function ajaxshowcomm() {
        $staple_id = intval(input('stapleid'));
        /**
         * 查询相应的商品分类id
         */
        $model_staple = Model('goodsclassstaple');
        $staple_info = $model_staple->getStapleInfo(array('staple_id' => intval($staple_id)), 'gc_id_1,gc_id_2,gc_id_3');
        if (empty ( $staple_info ) || ! is_array ( $staple_info )) {
            echo json_encode ( array (
                'done' => false,
                'msg' => ''
            ) );
            die ();
        }
        $list_array = array ();
        $list_array['gc_id'] = 0;
        $list_array['type_id'] = $staple_info['type_id'];
        $list_array['done'] = true;
        $list_array['one'] = '';
        $list_array['two'] = '';
        $list_array['three'] = '';
        $gc_id_1 = intval ( $staple_info['gc_id_1'] );
        $gc_id_2 = intval ( $staple_info['gc_id_2'] );
        $gc_id_3 = intval ( $staple_info['gc_id_3'] );
        /**
         * 查询同级分类列表
         */
        $model_goods_class = Model ( 'goodsclass' );
        // 1级
        if ($gc_id_1 > 0) {
            $list_array['gc_id'] = $gc_id_1;
            $class_list = $model_goods_class->getGoodsClass($_SESSION['store_id'],0,1,$_SESSION['seller_group_id'],$_SESSION['seller_gc_limits']);
            if (empty ( $class_list ) || ! is_array ( $class_list )) {
                echo json_encode ( array (
                    'done' => false,
                    'msg' => ''
                ) );
                die ();
            }
            foreach ( $class_list as $val ) {
                if ($val ['gc_id'] == $gc_id_1) {
                    $list_array ['one'] .= '<li class="" onclick="selClass($(this));" data-param="{gcid:' . $val ['gc_id'] . ', deep:1, tid:' . $val ['type_id'] . '}" nctype="selClass"> <a class="classDivClick" href="javascript:void(0)"><span class="has_leaf"><i class="icon-double-angle-right"></i>' . $val ['gc_name'] . '</span></a> </li>';
                } else {
                    $list_array ['one'] .= '<li class="" onclick="selClass($(this));" data-param="{gcid:' . $val ['gc_id'] . ', deep:1, tid:' . $val ['type_id'] . '}" nctype="selClass"> <a class="" href="javascript:void(0)"><span class="has_leaf"><i class="icon-double-angle-right"></i>' . $val ['gc_name'] . '</span></a> </li>';
                }
            }
        }
        // 2级
        if ($gc_id_2 > 0) {
            $list_array['gc_id'] = $gc_id_2;
            $class_list = $model_goods_class->getGoodsClass($_SESSION['store_id'], $gc_id_1, 2,$_SESSION['seller_group_id'],$_SESSION['seller_gc_limits']);
            if (empty ( $class_list ) || ! is_array ( $class_list )) {
                echo json_encode ( array (
                    'done' => false,
                    'msg' => ''
                ) );
                die ();
            }
            foreach ( $class_list as $val ) {
                if ($val ['gc_id'] == $gc_id_2) {
                    $list_array ['two'] .= '<li class="" onclick="selClass($(this));" data-param="{gcid:' . $val ['gc_id'] . ', deep:2, tid:' . $val ['type_id'] . '}" nctype="selClass"> <a class="classDivClick" href="javascript:void(0)"><span class="has_leaf"><i class="icon-double-angle-right"></i>' . $val ['gc_name'] . '</span></a> </li>';
                } else {
                    $list_array ['two'] .= '<li class="" onclick="selClass($(this));" data-param="{gcid:' . $val ['gc_id'] . ', deep:2, tid:' . $val ['type_id'] . '}" nctype="selClass"> <a class="" href="javascript:void(0)"><span class="has_leaf"><i class="icon-double-angle-right"></i>' . $val ['gc_name'] . '</span></a> </li>';
                }
            }
        }
        // 3级
        if ($gc_id_3 > 0) {
            $list_array['gc_id'] = $gc_id_3;
            $class_list = $model_goods_class->getGoodsClass($_SESSION['store_id'], $gc_id_2, 3,$_SESSION['seller_group_id'],$_SESSION['seller_gc_limits']);
            if (empty ( $class_list ) || ! is_array ( $class_list )) {
                echo json_encode ( array (
                    'done' => false,
                    'msg' => ''
                ) );
                die ();
            }
            foreach ( $class_list as $val ) {
                if ($val ['gc_id'] == $gc_id_3) {
                    $list_array ['three'] .= '<li class="" onclick="selClass($(this));" data-param="{gcid:' . $val ['gc_id'] . ', deep:3, tid:' . $val ['type_id'] . '}" nctype="selClass"> <a class="classDivClick" href="javascript:void(0)"><span class="has_leaf"><i class="icon-double-angle-right"></i>' . $val ['gc_name'] . '</span></a> </li>';
                } else {
                    $list_array ['three'] .= '<li class="" onclick="selClass($(this));" data-param="{gcid:' . $val ['gc_id'] . ', deep:3, tid:' . $val ['type_id'] . '}" nctype="selClass"> <a class="" href="javascript:void(0)"><span class="has_leaf"><i class="icon-double-angle-right"></i>' . $val ['gc_name'] . '</span></a> </li>';
                }
            }
        }
        // 转码
        if (strtoupper ( CHARSET ) == 'GBK') {
            $list_array = Language::getUTF8 ( $list_array );
        }
        echo json_encode ( $list_array );
        die ();
    }


    public function image_dir_type()
    {
        $model_setting = Model('setting');
        $ret = $model_setting->getRowSetting('image_dir_type');

        if ($ret['value'] == 1) {
            return '/shop/store/goods/' . $_SESSION['store_id'] . '/';
        } elseif ($ret['value'] == 2) {
            return '/shop/store/goods/' . $_SESSION['store_id'] . '/' . date("Y", time()) . '/';
        } elseif ($ret['value'] == 3) {
            return '/shop/store/goods/' . $_SESSION['store_id'] . '/' . date("Y", time()) . '/' . date("m", time()) . '/';
        } else {
            return '/shop/store/goods/' . $_SESSION['store_id'] . '/' . date("Y", time()) . '/' . date("m", time()) . '/' . date("d", time()) . '/';
        }
    }

    /**
     * 三方店铺验证，商品数量，有效期
     */
    private function checkStore()
    {
        $goodsLimit = (int)$this->store_grade['sg_goods_limit'];
        if ($goodsLimit > 0) {
            // 是否到达商品数上限
            $goods_num = Model('goods')->getGoodsCommonCount(array('store_id' => $_SESSION['store_id']));
            if ($goods_num >= $goodsLimit) {
                showMessage(L('store_goods_index_goods_limit') . $goodsLimit . L('store_goods_index_goods_limit1'), 'index.php?s=store_goods_online&op=goods_list', 'html', 'error');
            }
        }
    }
}